package com.example.lock;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.util.UUID;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-11-25 15:29
 */
@RestController
public class TestController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    @GetMapping("/test")
    public void test1() throws InterruptedException {
//        String lockKey = "testlock109";
//        String uuid = UUID.randomUUID().toString();
//        //抢锁
//        while(Boolean.FALSE.equals(stringRedisTemplate.opsForValue().setIfAbsent(lockKey, uuid
//                , Duration.ofSeconds(30)))){
//            Thread.sleep(50L);
//        }
//
//        try{
//            //抢到了
//            String stock = stringRedisTemplate.opsForValue().get("stock");
//            Long aLong = Long.valueOf(stock);
//            aLong--;
//            stringRedisTemplate.opsForValue().set("stock", aLong.toString());
//        }finally {
//            String s = stringRedisTemplate.opsForValue().get(lockKey);
//            if(uuid.equals(s)){
//                stringRedisTemplate.delete(lockKey);
//            }
//
//        }

        //获取锁
        RLock lock = redissonClient.getLock("testlock109-2");

        lock.lock();
        try{
            //抢到了
            String stock = stringRedisTemplate.opsForValue().get("stock");
            Long aLong = Long.valueOf(stock);
            aLong--;
            stringRedisTemplate.opsForValue().set("stock", aLong.toString());
        }finally {
            if(lock.isHeldByCurrentThread()){
                lock.unlock();
            }
        }


    }
}
